const { UPLOAD } = require("../../config/config.default");
const { validate } = require("./errorBack");
const { body } = require("express-validator");

module.exports = {
  upload: validate([
    body("title")
      .notEmpty()
      .withMessage("标题不能为空")
      .bail()
      .isLength({
        min: 6,
        max: 30,
      })
      .withMessage("标题长度需为6 ~ 30个字符"),
  ]),
};

module.exports.validateImg = (req, res, next) => {
  if (!req.file) {
    return res.status(400).json({ error: "请上传文件" });
  }

  // 验证文件类型
  const allowedTypes = ["image/jpeg", "image/png"];
  if (!allowedTypes.includes(req.file.mimetype)) {
    fs.unlink(req.file.path, (err) => {
      if (err) console.error("删除文件失败:", err);
    });
    return res.status(400).json({ error: "仅支持JPEG和PNG图片" });
  }

  // 验证文件大小
  if (req.file.size > UPLOAD.img.size) {
    fs.unlink(req.file.path, (err) => {
      if (err) console.error("删除文件失败:", err);
    });
    return res.status(400).json({ error: "文件大小不能超过5MB" });
  }

  next();
};
